<?php
/* Class file for a team */
class Team {
  var $id;
  var $coach;
  var $name;
  var $race;
  var $tr;
  var $roster;
  var $treasury;
  var $rerolls;
  var $fanFactor;
  var $coaches;
  var $cheerleaders;
  var $apothecary;
  var $moneyLent;
  var $players;
  var $conference;
  var $moneyBorrowed;
  var $lastUpdate;
  var $usesExp;
  var $comments;

  // Records
  var $stats; // all time stats - lazy
  var $currentSeasonStats;
  var $adjustment = 0;

  // team view customisation
  var $text = '#ffffff';
  var $background = '#aa0000';
  var $titleText = '#ffffff';
  var $titleBackground = '#000000';
  var $borderLight = '#c08040';
  var $borderDark = '#400000';
  

  function Team() {
  	$this->currentSeasonStats = new TeamStats();
  }

  function noSeasonLoad($team_id) {
  	$pd = new PlayerDao();
    $this->id = $team_id;
    $rs = executeQuery("select fk_coach_id, name, fk_race_id, team_rating, roster, treasury, money_lent, money_borrowed, rerolls, fanfactor, coaches, cheerleaders, apothecary, uses_exp, text_colour, background_colour, title_text_colour, title_background_colour, table_border_light, table_border_dark, date_format(last_update, '%b %e ''%y %H:%i'), comments from teams where team_id=$team_id");
    $row = mysql_fetch_row($rs);
    $i = 0;
    $this->coach = loadCoach($row[$i++]);
    $this->name = $row[$i++];
    $this->race = getRace($row[$i++]);
    $this->tr = $row[$i++];
    $this->roster = $row[$i++];
    $this->treasury = $row[$i++];
    $this->moneyLent = $row[$i++];
    $this->moneyBorrowed = $row[$i++];
    $this->rerolls = $row[$i++];
    $this->fanFactor = $row[$i++];
    $this->coaches = $row[$i++];
    $this->cheerleaders = $row[$i++];
    $this->apothecary = $row[$i++];
    $this->usesExp = $row[$i++] != 0;
    $this->text = $row[$i++];
    $this->background = $row[$i++];
    $this->titleText = $row[$i++];
    $this->titleBackground = $row[$i++];
    $this->borderLight = $row[$i++];
    $this->borderDark = $row[$i++];
    $this->lastUpdate = $row[$i++];
    $this->comments = $row[$i++];
    $this->players = $pd->loadPlayers($this);
  }

  function load($team_id) {
  	$pd = new PlayerDao();
  	global $races, $season;
    $this->id = $team_id;
    $rs = executeQuery("select fk_coach_id, name, fk_race_id, team_rating, roster, treasury, money_lent, money_borrowed, rerolls, fanfactor, coaches, cheerleaders, apothecary, uses_exp, text_colour, background_colour, title_text_colour, title_background_colour, table_border_light, table_border_dark, conference, date_format(last_update, '%b %e ''%y %H:%i'), comments, point_adjustment from teams, seasons_teams where team_id=$team_id and fk_team_id=team_id and fk_season_id=$season->id");
    $row = mysql_fetch_row($rs);
    $i = 0;
    $this->coach = loadCoach($row[$i++]);
    $this->name = $row[$i++];
    $this->race = getRace($row[$i++]);
    $this->tr = $row[$i++];
    $this->roster = $row[$i++];
    $this->treasury = $row[$i++];
    $this->moneyLent = $row[$i++];
    $this->moneyBorrowed = $row[$i++];
    $this->rerolls = $row[$i++];
    $this->fanFactor = $row[$i++];
    $this->coaches = $row[$i++];
    $this->cheerleaders = $row[$i++];
    $this->apothecary = $row[$i++];
    $this->usesExp = $row[$i++] != 0;
    $this->text = $row[$i++];
    $this->background = $row[$i++];
    $this->titleText = $row[$i++];
    $this->titleBackground = $row[$i++];
    $this->borderLight = $row[$i++];
    $this->borderDark = $row[$i++];
    $this->conference = $row[$i++];
    $this->lastUpdate = $row[$i++];
    $this->comments = $row[$i++];
    $this->adjustment = $row[$i++];
    $this->points = $this->adjustment;
    $this->players = $pd->loadPlayers($this);
  }
  
  function getPoints() {
      return ($this->currentSeasonStats->won * 3) + $this->currentSeasonStats->drawn + $this->adjustment;  
  }
  
  function getStats() {
      if (!isset($this->stats)) {
          $this->stats = new TeamStats($this);
      }
      return $this->stats;
  }

  function usesTeamEditor() {
    return (!isset($this->roster)) or strlen($this->roster) == 0;
  }

  function getValue($item) {
    if (isset($item)) {
      return $item;
    } else {
      return "null";
    }
  }

  function getRosterLink() {
    if ($this->usesTeamEditor()) {
      return "<a href=\"team_viewer.php?id=" . $this->id . "\">" . $this->getValue($this->name) . "</a>";
    } else {
      return "<a href=\"" . $this->getValue($this->roster) . "\">" . $this->getValue($this->name) . "</a>";
    }
  }

  function setRoster($roster, $roster_name, $url) {
    if(isset($roster) and $roster!="none") {
      $new_name = str_replace(" ", "_", $roster_name);
      $new_name = "rosters/" . $new_name;
      copy($roster, $new_name);
      $roster = $new_name;
      //chmod($roster, 666);
    } else {
      $roster=$url;
    }
    $this->roster = addslashes($roster);
  }

  function update($name, $race, $team_rating, $roster, $roster_name, $url) {
    $this->setRoster($roster, $roster_name, $url);
    $this->name = $name;
    $name = addslashes($this->name);
    $comments = addslashes($this->comments);
    $this->race = $race;
    $this->tr = $team_rating;
    $raceId = $this->race->id;
    return executeQuery("update teams set name='$name', fk_race_id='$raceId', team_rating='$this->tr', roster='$this->roster', comments='$comments', last_update=now() where team_id='$this->id'");
  }

  function save() {
    foreach ($this->players as $player) {
        $player->save($this);
    }

    $name = addslashes($this->name);
    $comments = addslashes($this->comments);
    $race_id = $this->race->id;

    return executeQuery("update teams set name='$name', fk_race_id=$race_id, treasury=$this->treasury, " .
    		"money_lent=$this->moneyLent, money_borrowed=$this->moneyBorrowed, rerolls=$this->rerolls, " .
    		"fanfactor=$this->fanFactor, coaches=$this->coaches, cheerleaders=$this->cheerleaders, " .
    		"apothecary=$this->apothecary, background_colour='$this->background', text_colour='$this->text', " .
    		"title_background_colour='$this->titleBackground', title_text_colour='$this->titleText', " .
    		"table_border_light='$this->borderLight', table_border_dark='$this->borderDark', roster=null, " .
    		"team_rating=null, last_update=now(), comments='$comments' where team_id=$this->id");
  }

  function updateAndAddPlayer($player, $rosterNum, $name, $position, $ma, $st, $ag, $av, $skills, $mng, $nig, $cp, $td, $in, $cas, $mvp, $exps, $cost) {
      $player->rosterNum = $rosterNum;
      $player->name= $name;
      $player->position = $position;
      $player->ma = $ma;
      $player->st = $st;
      $player->ag = $ag;
      $player->av = $av;
      $player->skills = $skills;
      $player->injured = "true" == $mng;
      $player->niggles = strlen($nig) > 0 ? $nig : 0;
      $player->completions = strlen($cp) > 0 ? $cp : 0;
      $player->tds = strlen($td) > 0 ? $td : 0;
      $player->interceptions = strlen($in) > 0 ? $in : 0;
      $player->casualties = strlen($cas) > 0 ? $cas : 0;
      $player->mvps = strlen($mvp) > 0 ? $mvp : 0;
      $player->exps = strlen($exps) > 0 ? $exps : 0;
      $player->cost = strlen($cost) > 0 ? $cost : 0;
      $this->setPlayer($player);
  }

  function updatePlayer($playerId, $rosterNum, $name, $position, $ma, $st, $ag, $av, $skills, $mng, $nig, $cp, $td, $in, $cas, $mvp, $exps, $cost) {
    $player = $this->getPlayerById($playerId);
    $cost = strlen($cost) > 0 ? $cost : 0;
    $name = stripcslashes($name);
    $position = stripcslashes($position);
    $skills = stripcslashes($skills);

    // is the player already in the team
    if (!$player)
    {
      // no player, and doesn't need removing
      if (0 == $cost)
      {
        return;
      }
      // new player
      $player = new Player();
      $this->updateAndAddPlayer($player, $rosterNum, $name, $position, $ma, $st, $ag, $av, $skills, $mng, $nig, $cp, $td, $in, $cas, $mvp, $exps, $cost);
    }
    else
    {
      if (0 == $cost)
      {
        // remove player from list & delete from db if
        $newPlayers = array();
        foreach ($this->players as $existingPlayer)
        {
          if ($existingPlayer->playerId != $player->playerId)
          {
            array_push($newPlayers, $existingPlayer);
          }
        }

        $this->players = $newPlayers;
        if ($player->isPersisted)
        {
          $player->dead();
        }
      }
      else
      {
        $this->updateAndAddPlayer($player, $rosterNum, $name, $position, $ma, $st, $ag, $av, $skills, $mng, $nig, $cp, $td, $in, $cas, $mvp, $exps, $cost);
      }
    }
  }

  function validateRosterNumbers()
  {
    $rosterNumUsed = array();
    $duplicatePlayers = array();
    for ($i = 0; $i < 16; $i++)
    {
      array_push($rosterNumUsed, false);
    }

    foreach ($this->players as $player)
    {
      if ($rosterNumUsed[$player->rosterNum-1])
      {
        array_push($duplicatePlayers, $player);
      }
      $rosterNumUsed[$player->rosterNum-1] = true;
    }

    foreach ($duplicatePlayers as $dupe)
    {
      for ($i = 0; $i < 16; $i++)
      {
        if (!$rosterNumUsed[$i])
        {
          $dupe->rosterNum = $i + 1;
          $rosterNumUsed[$i] = true;
          $this->setPlayer($dupe);
          break;
        }
      }
    }
  }

  function getPlayer($id) {
    foreach ($this->players as $player) {
      if ($player->rosterNum == $id) {
        return $player;
      }
    }
    return false;
  }

  function getPlayerById($id) {
    foreach ($this->players as $player) {
      if ($player->playerId == $id) {
        return $player;
      }
    }
    return false;
  }

  function setPlayer($newPlayer) {
    if ($newPlayer->playerId > -1) {
      for ($i = 0; $i < sizeof($this->players); $i++) {
        if ($this->players[$i]->playerId == $newPlayer->playerId) {
          $this->players[$i] = $newPlayer;
          return;
        }
      }
    }
    array_push($this->players, $newPlayer);
  }
  
  function changeRosterNumber(& $player, $newRosterNum) {
  	$existing = $this->getPlayer($newRosterNum);
  	if (isset($existing) && $existing) {
  	    for ($i = 1; $i < 17; $i++) {
  	        $rosterNum = $i + $existing->rosterNum;
  	        if ($rosterNum > 16) {
  	            $rosterNum -= 16;
  	        }
  	        if ($rosterNum == $player->rosterNum) {
			  	$existing->rosterNum = $rosterNum;
			  	$existing->save($this);
			  	$this->setPlayer($existing);
			  	break;
  	        } else {
  	        	$space = $this->getPlayer($rosterNum);
  	            if (isset($space) && $space) {
  	                continue;
  	            }
			  	$existing->rosterNum = $rosterNum;
			  	$existing->save($this);
			  	$this->setPlayer($existing);
			  	break;
  	        }
  	        
  	    }
  	}
  	$player->rosterNum=$newRosterNum;
  }

  function getSPPsTotal() {
    $spps = 0;
    foreach ($this->players as $player) {
      $spps += $player->getSPPS();
    }
    return $spps;
  }

  function getPlayerCostTotal() {
    $cost = 0;
    foreach ($this->players as $player) {
        if (!$player->injured) {
            $cost += $player->cost;
        }
    }
    return $cost;
  }

  function getTotalCost() {
  	$rerollCost = isset($this->race) ? $this->race->rerollCost : 50;
    return $this->getPlayerCostTotal()
      + ($this->rerolls * $rerollCost)
      + ($this->fanFactor * 10)
      + ($this->coaches * 10)
      + ($this->cheerleaders * 10)
      + ($this->apothecary * 50);
  }

  function getTR() {
      return $this->getTotalCost(); // + $this->treasury + $this->moneyLent;
  }

  /* Only remembers league results */
  function addResult($myMatchRecord, $opponentMatchRecord, $match) {
  	$this->currentSeasonStats->addMatch($myMatchRecord, $opponentMatchRecord, $match->id);
  }
}
?>